package com.banmoon.collection;

import java.util.*;

/**
 * 线程安全集合
 */
public class Demo2 {

    public static void main(String[] args) {
        testArrayList();
//        testHashMap();
//        testSet();
    }

    public static void testArrayList(){
        List<String> list = Collections.synchronizedList(new ArrayList<>());
        for (int i = 1; i <= 10; i++) {
            new Thread(() -> {
                list.add(Thread.currentThread().getName());
                System.out.println(list);
            }, "线程" + i).start();
        }
    }

    public static void testHashMap(){
        Map<Integer, String> map = Collections.synchronizedMap(new HashMap<>());
        for (int i = 0; i < 10; i++) {
            int temp = i;
            new Thread(() -> {
                map.put(temp, Thread.currentThread().getName());
                System.out.println(map);
            }, "线程" + i).start();
        }
    }

    public static void testSet(){
        Set<String> set = Collections.synchronizedSet(new TreeSet<>());
        for (int i = 1; i <= 10; i++) {
            new Thread(() -> {
                set.add(Thread.currentThread().getName());
                System.out.println(set);
            }, "线程" + i).start();
        }
    }

}
